package com.situ.stl.interceptor;



import com.situ.stl.constants.Constants;
import com.situ.stl.entity.Member;

import com.situ.stl.service.MemberService;
import com.situ.stl.util.JWTUtil;
import com.situ.stl.util.Result;
import io.jsonwebtoken.Claims;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 用户登录拦截器
 */
@Component
@Slf4j
public class MemberInterceptor implements HandlerInterceptor{

    @Autowired
    private MemberService memberService;

    /**
     * 拦截未登录用户
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  throws Exception{
        // 读取请求头中的Token
        String token = request.getHeader("token");

        String uri = request.getRequestURI();
        System.out.println("Member拦截器" + uri);

        // 当前登录用户
        Member member = null;
        // 有Token, 解析
        if ( StringUtils.hasText(token)) {
            // 尝试解析
            try {
                Claims claims = JWTUtil.parseJWT(token);
                String phone = claims.getSubject();
                member = memberService.getByPhone(phone);
            } catch (Exception e) {
                log.info("无效的token");
            }
        }

        if (!ObjectUtils.isEmpty(member)) {
            // 刷新Token
            String newToken = JWTUtil.createJWT(token);

            response.setHeader("token", newToken);

            return true;
        } else {
            response.setStatus(401);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(Result.error(Constants.STATUS_10001,"当前用户未登录或登录已过期！").toJson());
            return false;
        }
    }

}
